<template>
  <div>
    <tabled :list="list">
      <template #biaodan="{ item }">
        <!-- {{ item }} -->
        <button ref="edit" @click="edit(item)">编辑</button>
        <button @click="btn(item.id)">删除</button>
        <button ref="add" @click="add">添加</button>
      </template>
    </tabled>
    <dialogA :flag="flag" :title="title">
      <form>
        姓名:<input type="" name="" value="" v-model="newlist.name" />
        年龄:<input type="" name="" value="" v-model="newlist.age" />
        <div>
          <button @click="quxiao">取消</button>
          <button @click="quren">确认</button>
        </div>
      </form>
    </dialogA>
  </div>
</template>
<script>
import tabled from './tabs/MyTable.vue'
import dialogA from './tabs/dialog.vue'
export default {
  data () {
    return {
      list: [
        { id: 1, name: '赵云', age: 18 },
        { id: 2, name: '张角', age: 25 },
        { id: 3, name: '黄忠', age: 26 },
      ],
      flag: false,
      newlist: { name: '', age: '' },
      num: 1,
      title: '编辑页面'
    }
  },
  components: {
    tabled,
    dialogA
  },
  methods: {
    //1.点击删除
    btn (id) {
      console.log(id);
      this.list = this.list.filter(item => item.id !== id)
    },
    //2.点击编辑,弹出编辑对话框
    edit (item) {

      if (this.$refs.edit.innerHTML == '编辑') {
        this.title = '编辑页面'
        this.flag = true
        this.newlist = JSON.parse(JSON.stringify(item))
      }
    },
    //3.移除对话框
    quxiao () {
      this.flag = false
    },
    //4.点击修改数据
    quren () {
      if (this.title == '编辑页面') {
        let obj = this.list.find(item => item.id === this.newlist.id)
        console.log(obj);
        obj.name = this.newlist.name
        obj.age = this.newlist.age
        this.flag = false
      } else if (this.title == '添加页面') {
        if (this.newlist.name == '' || this.newlist.age == '') {
          return alert('请输入内容')
        } else {
          console.log(this.newlist);
          this.list.push({
            id: Date.now(),
            ...this.newlist
          })
        }
        this.flag = false
      }
    },
    //5.添加
    add () {
      this.title = '添加页面'
      this.flag = true
      this.newlist = { name: '', age: '' }
    }
  }
}
</script>

<style>
body {
  background-color: #b3b3b3;
}
</style>